package com.github.bryx.workflow.referenceobject;

import com.github.bryx.workflow.exception.WorkflowRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

/**
 *
 * 引用对象加载器的加载
 * @Author jameswu
 * @Date 2021/7/21
 **/
@Component
@Slf4j
public class ReferenceObjectLoaderRegistry implements InitializingBean {

    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(Loader.class);
        if (beanNamesForAnnotation.length==0){
            return;
        }
        ReferenceObjectService referenceObjectService = applicationContext.getBean(ReferenceObjectService.class);
        for (String beanName : beanNamesForAnnotation){
            Object bean = applicationContext.getBean(beanName);
            if (!(bean instanceof ReferenceObjectLoader)){
                throw new WorkflowRuntimeException(String.format("%s must implement interface $s",bean.getClass(), ReferenceObjectLoader.class));
            }
            Loader annotation = AnnotationUtils.findAnnotation(bean.getClass(), Loader.class);
            Class[] types = annotation.type();
            for(Class type : types){
                referenceObjectService.registerLoader(type, (ReferenceObjectLoader)bean);
                log.debug("register reference object loader 【{}】 on class【{}】", bean.getClass(), type);
            }
        }
    }
}
